package com.me.study.concurrent.threadUtil;

import com.me.common.util.SleepUtil;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch 测试类:<p>
 *
 * PS: 发现了 Junit 和 main 方法执行任务的线程不一样：<p>
 *     1, Junit 线程执行完成后，未完成的子线程会被杀掉
 *     2, main 方法开启的线程完成后，未完成的子线程会继续执行
 *
 * @author ME
 * @date   2019/5/29
 */
public class TestCountDownLatch {

    @Test
    public void test() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);
        Thread.currentThread().setName("ME-thread-main");

        // await 线程
        new Thread(() -> {
            Thread.currentThread().setName("ME-await");
            SleepUtil.seconds(3);
            try {
                System.out.println("线程: ME-await             开始await了");
                latch.await();

                SleepUtil.seconds(8);
                System.out.println("线程: ME-await             退出await");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // countDown 线程
        Thread.currentThread().setName("ME-thread-main");
        new Thread(() -> {
            Thread.currentThread().setName("ME-Count1");
            SleepUtil.seconds(3);
            latch.countDown();
        }).start();

        // countDown 线程
        new Thread(() -> {
            Thread.currentThread().setName("ME-Count2");
            SleepUtil.seconds(10);
            latch.countDown();
        }).start();

        System.out.println("线程: ME-thread-main       开始await");
        latch.await();

        SleepUtil.seconds(3);
        System.out.println("线程: ME-thread-main       退出await");
    }

    public static void main(String[] args) throws InterruptedException {
        TestCountDownLatch testCountDownLatch = new TestCountDownLatch();
        testCountDownLatch.test();
    }
}
